package leetcode.editor.cn;

/**
 * @id: 219
 * @title: 存在重复元素 II
 */
 
//给定一个整数数组和一个整数 k，判断数组中是否存在两个不同的索引 i 和 j，使得 nums [i] = nums [j]，并且 i 和 j 的差的 绝对值
// 至多为 k。 
//
// 
//
// 示例 1: 
//
// 输入: nums = [1,2,3,1], k = 3
//输出: true 
//
// 示例 2: 
//
// 输入: nums = [1,0,1,1], k = 1
//输出: true 
//
// 示例 3: 
//
// 输入: nums = [1,2,3,1,2,3], k = 2
//输出: false 
// Related Topics 数组 哈希表 滑动窗口 
// 👍 340 👎 0

public class P219ContainsDuplicateIi {
    public static void main(String[] args) {
        Solution solution = new P219ContainsDuplicateIi().new Solution();
        // todo
        boolean result = solution.containsNearbyDuplicate(new int[]{1,2,3,1}, 2);
//        result = solution.containsNearbyDuplicate(new int[]{1,0,1,1}, 1);
//        result &= solution.containsNearbyDuplicate(new int[]{1,2,3,1}, 2);
        result &= solution.containsNearbyDuplicate(new int[]{1,2,3,1,2,3}, 2);
        System.out.println(result);
    }
    
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        int len = nums.length;
        boolean result = false;
        for (int i = 0; i < len; ++i) {
            for (int j = i+1; j < len && Math.abs(i - j) <= k; ++j) {
                if (nums[i] == nums[j]) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }
}
//leetcode submit region end(Prohibit modification and deletion)


}